package pl.edu.pw.elka.tinyrepo.gate;


import java.io.File;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;


import pl.edu.pw.elka.tinyrepo.gate.descriptor.RepoDescriptor;
import pl.edu.pw.elka.tinyrepo.gate.server.GateFacade;
import pl.edu.pw.elka.tinyrepo.gate.server.GateFacadeImpl;
import pl.edu.pw.elka.tinyrepo.gate.server.GateServer;


// FIXME zaimplementowac

/**
 * Main bramy.
 * 
 * @author Piotr Jarosik
 */
public class GateMain {
	
   static final String appString = "tinyrepo gate v.0.1";
   /**
    * Wypisuje info o bramie na standardowe wyjscie.
    * 
    * @param args
    */
   static void printGateInfo(GateArgumentLineParser args) {
     System.out.println(appString);
     System.out.println("port: "+args.getPort());
   }
   
   static void startRMI(GateFacade f) {
      Registry r;
      try {
         r = LocateRegistry.getRegistry();
         GateFacade stub = (GateFacade)UnicastRemoteObject.exportObject(f, 0);
         r.rebind("gate", stub);
         System.out.println("Registered in RMI...");
      } catch (RemoteException e) {
         System.out.println("Couldnt connect with RMI registry ...");
         System.exit(-1);
      }
   }
   /**
    * Main main...
    * 
    * @param args
    */
   public static void main(String[] args) {
      GateArgumentLineParser gateArgs = new GateArgumentLineParser();
      try {
         gateArgs.parse(args); // pobieranie argumentow
      }
      catch (Exception e) {
         e.printStackTrace();
      }
      printGateInfo(gateArgs); // wypisanie info o serwerze
     
      // zaladowanie deskryptora repozytorium
      final File file = new File(gateArgs.getRepoFile());
         final RepoDescriptor desc = new RepoDescriptor(file);
         //TODO na razie tworzone puste repozytorium
         
      Runtime.getRuntime().addShutdownHook(new Thread() {    // dodanie operacji na SIGINT
        @Override
      public void run() {
           desc.writeToFile(file);
        } 
      });
      // uruchom serwer
      GateServer srv = new GateServer(gateArgs.getPort(), desc, gateArgs.getRepoFile());
//      srv.putFile("/plik", 11, 100L, "127.0.1.1:9009"); // DEBUG: testowo dodany plik o id 11
      GateFacade f = new GateFacadeImpl(srv);
      startRMI(f);
      srv.start();
   }
}